home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Power Programmierung
/
Power-Programmierung (Tewi)(1994).iso
/
magazine
/
ins_msc
/
imc9102
/
dynarray.c
next >
Wrap
Text File
|
1991-01-08
|
3KB
|
86 lines
/****************************************************************
* DYNARRAY.C - a demonstration of a dynamic array *
* *
* To compile with dynamic array: cl /DDYNAMIC dynarray.c *
* To compile with static array: cl dynarray.c *
****************************************************************/
#include <stdio.h> /* printf() */
#include <stdlib.h> /* qsort() */
#include <string.h> /* strcpy() */
struct Record
{
char Name[30]; /* Person's name */
int Ext; /* Telephone extension */
};
#ifdef DYNAMIC /* If dynamic array, declare pointer to array */
struct Record *Data=(struct Record *)NULL;
#else /* If not dynamic array, declare entire array */
struct Record Data[100];
#endif
/****************************************************************
* RecordCompare - compare two Record structures, and return *
* -1 if the first record should be first, +1 if the second *
* record should be first, and 0 if it doesn't matter *
****************************************************************/
int RecordCompare(void *a, void *b)
{
if ( ((struct Record *)a)->Ext < ((struct Record *)b)->Ext )
return -1;
if ( ((struct Record *)a)->Ext > ((struct Record *)b)->Ext )
return 1;
return 0;
}
/****************************************************************
* main - initialize the Data array, sort it by the telephone *
* extension field, and print the telephone list *
****************************************************************/
void main(void)
{
int i;
#ifdef DYNAMIC /* If we use dynamic array, allocate RAM for it */
Data = (struct Record *)calloc(9,sizeof(struct Record));
if (Data == NULL)
{
fputs("ERROR! couldn't allocate enough RAM!\n",stderr);
exit(1);
}
#endif
/* Handy shorthand for initializing the array */
#define INITIALIZE(y,z) strcpy(Data[i].Name,y);Data[i].Ext=z; i++
/*** Set up the data in the array ***/
i=0;
INITIALIZE("Marco C. Mason", 566);
INITIALIZE("Mark W. Crane", 531);
INITIALIZE("Jody Gilbert", 507);
INITIALIZE("Duane Spurlock", 528);
INITIALIZE("Tara Billinger", 539);
INITIALIZE("Tim Landgrave", 556);
INITIALIZE("Douglas Cobb", 523);
INITIALIZE("Maureen Pawley", 508);
INITIALIZE("Karl Feige", 559);
/*** Sort the list by telephone extension ***/
qsort(Data, 9, sizeof(struct Record),RecordCompare);
/*** Print the resulting phone list ***/
#ifdef DYNAMIC
puts("Phone list output (using DYNAMIC array)");
#else
puts("Phone list output (using STATIC array)");
#endif
puts("\nRecord Telephone\nNumber Extension Name");
for (i=0; i<9; i++)
printf(" %02d %03d %s\n",
i+1, Data[i].Ext, Data[i].Name);
}